<?php
/**
 * 搜索
 * Created by PhpStorm.
 * User: Egor <http://gitee.com/seosite>
 * Date: 2018/5/14
 * Time: 下午6:24
 * Updatetime:
 * updater：
 */
namespace Wap\Controller;
use Think\Controller;

class SearchController extends Controller
{
    /**
     * @desc 首页搜索
     * @author Egor<http://gitee.com/seosite>
     * @param $param
     * @return array
     */
    public function index($param)
    {
        $check = CheckFactoryController::isChildParamSet();
        $check->before('order,type,keyword');

        unset($check);

        $p = empty($param['p']) ?: $param['p'];
        $listRows = empty($param['listRows']) ? 20 : $param['listRows'];

        $len_keyword = mb_strwidth($param['keyword']);
        if ($len_keyword < 4) return showErrorMsg('关键字中文个数需要大于等于2，英文字母个数大于等于4',100002);

        $esObj = new ElasticSearchController();

        $tbName = $param['type'];

        if (empty($tbName)){
            $search_data = [
                'title' =>  $param['keyword']
            ];
        }else{
            $search_data = [
                'title' =>  $param['keyword'],
                'type'  =>  $tbName,
            ];
        }

        $from = ($p-1)*$listRows;

        $size = $listRows;

        $sortName = $param['order']==1?'create_time':'views';

        return $esObj->filterSearch($search_data,$from,$size,$sortName,'desc');
    }

    /**
     * @desc 添加
     * @author Egor<http://gitee.com/seosite>
     * @param $data ['work_id'=>'video_1','id'=>1,'title'=>'大家新年好啊','message'=>'','type'=>'video','views'=>0,'uid'=>0,'create_time'=>time(),'created'=>date('Y-m-d',time())]
     *
     */
    public function afterAdd($data)
    {
        $esObj = new ElasticSearchController();
        $esObj->afterAdd($data);
    }

    /**
     * @desc 删除
     * @author Egor<http://gitee.com/seosite>
     * @param $id | direct_1
     * @data ['index':'finance','type':'direct','id':'direct_1']
     */
    public function afterDel($id)
    {
        $idArr = explode('_',$id);

        $data = [
            'index' =>  'finance',
            'type' =>  $idArr[0],
            'id' =>  $id,
        ];
        $esObj = new ElasticSearchController();
        $ret = $esObj->afterDel($data);
    }

    /**
     * @desc 修改
     * @author Egor<http://gitee.com/seosite>
     * @param $data
     */
    public function afterUpdate($data)
    {
        $esObj = new ElasticSearchController();
        if (!empty($data['created'])){
            $data['created'] = date('Y-m-d',$data['create_time']);
        }
        $ret = $esObj->afterAdd($data);
//        return $ret;
    }
}